#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>
#include "logger.h"

// 全局日志文件指针
FILE *access_log = NULL;
FILE *error_log = NULL;

// 初始化日志文件
int init_loggers() {
    access_log = fopen("access.log", "a");
    if (access_log == NULL) {
        perror("Failed to open access.log");
        return -1;
    }
    error_log = fopen("error.log", "a");
    if (error_log == NULL) {
        perror("Failed to open error.log");
        fclose(access_log);
        return -1;
    }
    return 0;
}

// 关闭日志文件
void close_loggers() {
    if (access_log != NULL) {
        fclose(access_log);
    }
    if (error_log != NULL) {
        fclose(error_log);
    }
}

// 记录访问日志
void log_access(const struct sockaddr_in *client_addr, const char *method, const char *uri, int status) {
    if (access_log == NULL) return;

    time_t now = time(NULL);
    struct tm *tm_info = localtime(&now);
    char time_str[26];
    strftime(time_str, sizeof(time_str), "%d/%b/%Y:%H:%M:%S %z", tm_info);

    fprintf(access_log, "%s - - [%s] \"%s %s HTTP/1.1\" %d -\n",
            inet_ntoa(client_addr->sin_addr),
            time_str,
            method,
            uri,
            status);
    fflush(access_log);
}

// 记录错误日志
void log_error(const char *message, int errnum) {
    if (error_log == NULL) return;

    time_t now = time(NULL);
    struct tm *tm_info = localtime(&now);
    char time_str[26];
    strftime(time_str, sizeof(time_str), "%d/%b/%Y:%H:%M:%S %z", tm_info);

    fprintf(error_log, "[%s] [core:error] %s: %s\n",
            time_str,
            message,
            strerror(errnum));
    fflush(error_log);
}
